package com.decent.manager.config.security;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.log.Log;
import com.decent.manager.system.cache.ResourceCache;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * 获取系统中所有@RequestMapping标注的接口
 *
 * @className: ResourceCollectListener
 * @author: wangyan
 * @date: 2022/6/21
 **/
@Component
public class ResourceCollectListener implements CommandLineRunner {

    private static final Log log = Log.get();

    @Resource
    private ResourceCache<Set<String>> resourceCache;
    @Override
    public void run(String... args) {
        //获取所有后端接口
        Set<String> urlSet = CollectionUtil.newHashSet();
        Map<String, RequestMappingHandlerMapping> mappingMap = SpringUtil.getApplicationContext().getBeansOfType(RequestMappingHandlerMapping.class);
        Collection<RequestMappingHandlerMapping> mappings = mappingMap.values();
        for (RequestMappingHandlerMapping mapping : mappings) {
            Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
            map.keySet().forEach(requestMappingInfo -> {
                assert requestMappingInfo.getPatternsCondition() != null;
                Set<String> patterns = requestMappingInfo.getPatternsCondition().getPatterns();
                urlSet.addAll(patterns);
            });
        }
        // 添加到缓存
        Set<String> urlSetCache = resourceCache.get(ResourceCache.URL_CACHE);
        if (CollectionUtil.isEmpty(urlSetCache)) {
            urlSetCache = new HashSet<>();
        }
        urlSetCache.addAll(urlSet);
        resourceCache.put(ResourceCache.URL_CACHE, urlSetCache);
        log.info("缓存资源URL集合完成，资源数量：{}", urlSet.size());
    }
}
